package org.wedding.center.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import org.wedding.center.dto.query.AttachQuery;
import org.wedding.center.dto.query.MerchantQuery;
import org.wedding.center.dto.query.ServiceQuery;
import org.wedding.center.dto.vo.AttachVo;
import org.wedding.center.dto.vo.MerchantVo;
import org.wedding.center.entity.AttachInfo;
import org.wedding.center.entity.ServiceInfo;
import org.wedding.center.entity.ServiceType;
import org.wedding.center.mapper.AttachInfoMapper;
import org.wedding.center.mapper.OrderInfoMapper;
import org.wedding.center.mapper.ServiceInfoMapper;
import org.wedding.center.mapper.ServiceTypeMapper;
import org.wedding.center.service.ServiceInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.wedding.enums.system.ResultCodeEnum;
import org.wedding.system.entity.UserInfo;
import org.wedding.system.mapper.UserMapper;
import org.wedding.utils.CommonResult;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.ObjectUtil;
import org.wedding.dto.PageModel;
import org.wedding.utils.PageUtil;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务信息表(ServiceInfo)表服务实现类
 *
 * @author songkaiyue
 * @since 2025-05-19 17:26:20
 */
@Service
public class ServiceInfoServiceImpl extends ServiceImpl<ServiceInfoMapper, ServiceInfo> implements ServiceInfoService {
    @Resource
    private OrderInfoMapper orderInfoMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ServiceInfoMapper serviceInfoMapper;
    @Resource
    private AttachInfoMapper attachInfoMapper;
    @Resource
    private ServiceTypeMapper serviceTypeMapper;


    /**
     * 小程序首页 查询商家列表信息
     *
     * @return
     */
    @Override
    public List<MerchantVo> findMerchants(MerchantQuery query) {
        try {
            List<MerchantVo> vos = new LinkedList<>();
            //没有地址的商家列表-排在最后
            List<MerchantVo> vos1 = new LinkedList<>();
            //查询商户列表
            List<UserInfo> userInfoList = userMapper.findMerchants(query);
            if (!userInfoList.isEmpty()) {
                for (UserInfo userInfo : userInfoList) {
                    ServiceInfo serviceInfo = serviceInfoMapper.findByUserIdOne(userInfo.getId());
                    int num = serviceInfoMapper.findByUserIdNum(userInfo.getId());
                    if (ObjectUtil.isEmpty(num)){
                        num = 0;
                    }
                    BigDecimal minPrice = BigDecimal.ZERO;
                    String imgUrl = "";
                    if (ObjectUtil.isNotEmpty(serviceInfo)) {
                        minPrice = serviceInfo.getAmount();
                        imgUrl = serviceInfo.getImgUrl();
                    }

                    UserInfo userInfo3 = userMapper.selectById(serviceInfo.getUserId());
                    MerchantVo vo = MerchantVo.builder()
                            .id(userInfo.getId())
                            .name(userInfo.getMerchantName())
                            .address(userInfo.getAddress())
                            .phone(userInfo.getContactPhone())
                            .imgurl(userInfo3.getIconUrl())
                            .distance(userInfo.getDistance())
                            .minPrice(minPrice.toPlainString())
                            .num(num + "")
                            .orderNum(userInfo.getOrderNum())
                            .build();
                    Boolean  isFormat=false;
                    Boolean  isFormat1=false;
                    //服务款式筛选
                    if (StrUtil.isNotEmpty(query.getFormat())){
                        List<ServiceInfo> infos = serviceInfoMapper.findByForMatat(query.getFormat());
                        if (!infos.isEmpty()){
                            if (StrUtil.isNotEmpty(userInfo.getLatitude()) && StrUtil.isNotEmpty(userInfo.getLongitude())) {
                                vos.add(vo);
                                isFormat=true;
                            }else {
                                vos1.add(vo);
                                isFormat1=true;
                            }
                        }
                    }
                    //价格区间筛选
                    if(!StrUtil.isEmpty(query.getPriceSection())){
                        ServiceType serviceType = serviceTypeMapper.findById(query.getPriceSection());
                        if (serviceType != null) {
                            if (serviceType.getPriceStart().compareTo(minPrice) <= 0 && serviceType.getPriceEnd().compareTo(minPrice) >= 0) {
                               if((isFormat &&  isFormat1 ) ||   StrUtil.isEmpty(query.getFormat())){
                                   if (StrUtil.isNotEmpty(userInfo.getLatitude()) && StrUtil.isNotEmpty(userInfo.getLongitude())) {
                                       vos.add(vo);
                                   }else {
                                       vos1.add(vo);
                                   }
                               }
                            }else{
                                if(isFormat){
                                   // vos 删除最后一个
                                    vos.remove(vos.size()-1);
                                }else if(isFormat1){
                                    vos1.remove(vos1.size()-1);
                                }


                            }
                        }
                    }
                    //无排序
                    if (StrUtil.isEmpty(query.getFormat()) && StrUtil.isEmpty(query.getPriceSection())){
                        if (StrUtil.isNotEmpty(userInfo.getLatitude()) && StrUtil.isNotEmpty(userInfo.getLongitude())) {
                            vos.add(vo);
                        }else {
                            vos1.add(vo);
                        }
                    }
                }
            }
            vos.addAll(vos1);
            // 去重复
            vos = vos.stream().distinct().collect(Collectors.toList());
            //热门排序
            if (StrUtil.isNotEmpty(query.getPopularSort())) {
                if (query.getPopularSort().equals("0")) {
                    // 对setList按照orderNum订单数量进行从大到小排序
                    Collections.sort(vos, (s1, s2) -> Integer.compare(Integer.parseInt(s2.getOrderNum()), Integer.parseInt(s1.getOrderNum())));
                } else {
                    // 对setList按照orderNum订单数量进行从小到大排序
                    Collections.sort(vos, (s1, s2) -> Integer.compare(Integer.parseInt(s1.getOrderNum()), Integer.parseInt(s2.getOrderNum())));
                }
            }
            //价格排序
            if (StrUtil.isNotEmpty(query.getPriceSort())) {
                if (query.getPriceSort().equals("0")) {
                    // 对setList按照price价格进行从大到小排序
                    Collections.sort(vos, (s1, s2) -> Double.compare(Double.parseDouble(s2.getMinPrice()), Double.parseDouble(s1.getMinPrice())));
                } else {
                    // 对setList按照price价格进行从小到大排序
                    Collections.sort(vos, (s1, s2) -> Double.compare(Double.parseDouble(s1.getMinPrice()), Double.parseDouble(s2.getMinPrice())));
                }
            }
            return vos;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据id查询商家信息
     * @param id
     * @return
     */
    @Override
    public CommonResult<MerchantVo> findMerchantById(String id, String latitude, String longitude) {
        try{
            UserInfo userInfo = userMapper.findMerchantById(id, latitude, longitude);
            List<ServiceInfo> serviceInfos = serviceInfoMapper.findByUserId(userInfo.getId());
            BigDecimal minPrice = BigDecimal.ZERO;
            int num = 0;
            String imgUrl = "";
            if (!serviceInfos.isEmpty()) {
                minPrice = serviceInfos.get(0).getAmount();
                num = serviceInfos.size();
                imgUrl = serviceInfos.get(0).getImgUrl();
            }
            MerchantVo vo = MerchantVo.builder()
                    .id(userInfo.getId())
                    .name(userInfo.getMerchantName())
                    .address(userInfo.getAddress())
                    .phone(userInfo.getContactPhone())
                    .imgurl(userInfo.getIconUrl())
                    .meUrl(userInfo.getMeUrl())
                    .distance(userInfo.getDistance())
                    .minPrice(minPrice.toPlainString())
                    .num(num + "")
                    .orderNum(userInfo.getOrderNum())
                    .build();
            return CommonResult.success(vo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    /**
     * 分页查询所有数据
     *
     * @return
     */
    @Override
    public CommonResult<PageModel> findAll(ServiceQuery query) {
        try {
            if (StrUtil.isNotEmpty(query.getPriceSection())) {
                ServiceType serviceType = serviceTypeMapper.findById(query.getPriceSection());
                if (serviceType != null) {
                    query.setPriceStart(serviceType.getPriceStart().toPlainString());
                    query.setPriceEnd(serviceType.getPriceEnd().toPlainString());
                }
            }
            List<ServiceInfo> list = baseMapper.selectAll(query);
            List<ServiceInfo> setList = query.setList(PageUtil.getListPage(query.getCurrent(), query.getPageSize(), list), list.size());
            if (StrUtil.isNotEmpty(query.getPriceSort())) {
                if (query.getPriceSort().equals("0")) {
                    // 对setList按照price价格进行从大到小排序
                    Collections.sort(setList, (s1, s2) -> Double.compare(Double.parseDouble(s2.getAmount().toPlainString()), Double.parseDouble(s1.getAmount().toPlainString())));
                } else {
                    // 对setList按照price价格进行从小到大排序
                    Collections.sort(setList, (s1, s2) -> Double.compare(Double.parseDouble(s1.getAmount().toPlainString()), Double.parseDouble(s2.getAmount().toPlainString())));
                }
            }
            if (StrUtil.isNotEmpty(query.getPopularSort())) {
                if (query.getPopularSort().equals("0")) {
                    // 对setList按照orderNum订单数量进行从大到小排序
                    Collections.sort(setList, (s1, s2) -> Integer.compare(Integer.parseInt(s2.getOrderNum()), Integer.parseInt(s1.getOrderNum())));
                } else {
                    // 对setList按照orderNum订单数量进行从小到大排序
                    Collections.sort(setList, (s1, s2) -> Integer.compare(Integer.parseInt(s1.getOrderNum()), Integer.parseInt(s2.getOrderNum())));
                }
            }
            query.setList(setList, list.size());
            return CommonResult.success(query);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }

    }

    /**
     * 根据id查看详情
     *
     * @param id
     * @return
     */
    @Override
    public CommonResult<ServiceInfo> view(String id) {
        try {
            ServiceInfo serviceInfo = baseMapper.findById(id);
            List<AttachVo> attachVos = new ArrayList<>();
            List<AttachInfo> attachInfos = attachInfoMapper.selectAll(AttachQuery.builder().businessId(id).build());
            if (!attachInfos.isEmpty()) {
                for (AttachInfo attachInfo : attachInfos) {
                    attachVos.add(AttachVo.builder()
                            .id(attachInfo.getId())
                            .name(attachInfo.getAttachName())
                            .url(attachInfo.getFilePath())
                            .status("success")
                            .build());
                }
            }
            serviceInfo.setAttachInfos(attachVos);
            return CommonResult.success(serviceInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 新增数据
     *
     * @param serviceInfo
     * @return
     */
    @Override
    public CommonResult add(ServiceInfo serviceInfo) {
        try {
            serviceInfo.setId(IdUtil.simpleUUID());
            serviceInfo.setCreateTime(DateUtil.now());
            serviceInfo.setDelFlag("0");
            String userId = StpUtil.getSession().get("userId").toString();
            serviceInfo.setUserId(userId);
            baseMapper.insert(serviceInfo);
            if (ObjectUtil.isNotEmpty(serviceInfo.getAttachIds()) && !serviceInfo.getAttachIds().isEmpty()){
                serviceInfo.getAttachIds().forEach(attachId -> {
                    AttachInfo attach = attachInfoMapper.selectById(attachId);
                    if (ObjectUtil.isNotEmpty(attach)){
                        attach.setBusinessId(serviceInfo.getId());
                        attach.setUpdateTime(DateUtil.now());
                        attachInfoMapper.updateById(attach);
                    }
                });
            }
            return CommonResult.success(serviceInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 修改数据
     *
     * @param serviceInfo
     * @return
     */
    @Override
    public CommonResult updateEntity(ServiceInfo serviceInfo) {
        try {
            serviceInfo.setUpdateTime(DateUtil.now());
            baseMapper.updateById(serviceInfo);
            if (ObjectUtil.isNotEmpty(serviceInfo.getAttachIds()) && !serviceInfo.getAttachIds().isEmpty()){
                serviceInfo.getAttachIds().forEach(attachId -> {
                    AttachInfo attach = attachInfoMapper.selectById(attachId);
                    if (ObjectUtil.isNotEmpty(attach)){
                        attach.setBusinessId(serviceInfo.getId());
                        attach.setUpdateTime(DateUtil.now());
                        attachInfoMapper.updateById(attach);
                    }
                });
            }
            return CommonResult.success(serviceInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 删除数据
     *
     * @param ids
     * @return
     */
    @Override
    public CommonResult delete(List<String> ids) {
        try {
            if (ObjectUtil.isEmpty(ids)) {
                return CommonResult.failed(ResultCodeEnum.PARAM_ERROR);
            }
            for (String id : ids) {
                baseMapper.upDeleteById(id);
            }
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

}
